const express = require('express');
const router = express.Router();
const { generateSudokuPuzzle, solveSudoku, isValidSudoku } = require('../utils/sudoku');

// 获取数独题目
router.get('/puzzle/:difficulty', async (req, res) => {
  try {
    const { difficulty } = req.params;
    
    // 验证难度参数
    const validDifficulties = ['easy', 'medium', 'hard', 'expert'];
    if (!validDifficulties.includes(difficulty)) {
      return res.status(400).json({ error: '无效的难度等级' });
    }
    
    // 生成数独题目
    const puzzle = generateSudokuPuzzle(difficulty);
    
    res.json({
      success: true,
      data: {
        puzzle: puzzle.puzzle,
        solution: puzzle.solution,
        difficulty: difficulty,
        id: Date.now().toString() // 简单的题目ID
      }
    });
  } catch (error) {
    console.error('生成题目失败:', error);
    res.status(500).json({ error: '生成题目失败' });
  }
});

// 提交游戏结果
router.post('/submit', async (req, res) => {
  try {
    const { puzzle, solution, difficulty, score, time, completed } = req.body;
    
    // 验证必需参数
    if (!puzzle || !difficulty || score === undefined || time === undefined) {
      return res.status(400).json({ error: '缺少必需参数' });
    }
    
    // 验证分数和时间的合理性
    if (score < 0 || time < 0) {
      return res.status(400).json({ error: '分数和时间必须为正数' });
    }
    
    const db = req.app.locals.db;
    
    // 保存游戏记录
    const [result] = await db.execute(
      'INSERT INTO games (puzzle, solution, difficulty, score, time_spent, completed, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [JSON.stringify(puzzle), JSON.stringify(solution), difficulty, score, time, completed ? 1 : 0]
    );
    
    const gameId = result.insertId;
    
    // 如果游戏完成，获取排名信息
    let rankInfo = null;
    if (completed) {
      try {
        // 获取分数排名
        const [scoreRank] = await db.execute(`
          SELECT COUNT(*) + 1 as rank
          FROM games 
          WHERE completed = 1 
            AND difficulty = ?
            AND (score > ? OR (score = ? AND time_spent < ?))
        `, [difficulty, score, score, time]);
        
        // 获取该难度下的总完成游戏数
        const [totalGames] = await db.execute(
          'SELECT COUNT(*) as total FROM games WHERE completed = 1 AND difficulty = ?',
          [difficulty]
        );
        
        rankInfo = {
          rank: scoreRank[0].rank,
          total: totalGames[0].total,
          percentage: Math.round((1 - (scoreRank[0].rank - 1) / totalGames[0].total) * 100)
        };
        
        console.log(`🎉 游戏完成! 玩家在${difficulty}难度下排名第${rankInfo.rank}位`);
      } catch (rankError) {
        console.error('获取排名信息失败:', rankError);
        // 排名获取失败不影响游戏保存
      }
    }
    
    res.json({
      success: true,
      data: {
        gameId: gameId,
        message: completed ? '恭喜完成游戏！成绩已保存到排行榜' : '游戏进度已保存',
        completed: completed,
        score: score,
        time: time,
        difficulty: difficulty,
        rank: rankInfo // 包含排名信息
      }
    });
    
  } catch (error) {
    console.error('保存游戏结果失败:', error);
    res.status(500).json({ error: '保存游戏结果失败' });
  }
});

// 获取游戏历史
router.get('/history', async (req, res) => {
  try {
    const { page = 1, limit = 10, difficulty } = req.query;
    const offset = (page - 1) * limit;
    
    const db = req.app.locals.db;
    
    let query = 'SELECT id, difficulty, score, time_spent, completed, created_at FROM games';
    let params = [];
    
    if (difficulty) {
      query += ' WHERE difficulty = ?';
      params.push(difficulty);
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));
    
    const [games] = await db.execute(query, params);
    
    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM games';
    let countParams = [];
    
    if (difficulty) {
      countQuery += ' WHERE difficulty = ?';
      countParams.push(difficulty);
    }
    
    const [countResult] = await db.execute(countQuery, countParams);
    const total = countResult[0].total;
    
    res.json({
      success: true,
      data: {
        games,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取游戏历史失败:', error);
    res.status(500).json({ error: '获取游戏历史失败' });
  }
});

// 验证数独解答
router.post('/validate', (req, res) => {
  try {
    const { grid } = req.body;
    
    if (!grid || !Array.isArray(grid)) {
      return res.status(400).json({ error: '无效的数独网格' });
    }
    
    const isValid = isValidSudoku(grid);
    
    res.json({
      success: true,
      data: {
        isValid,
        message: isValid ? '数独解答正确！' : '数独解答有误'
      }
    });
  } catch (error) {
    console.error('验证数独失败:', error);
    res.status(500).json({ error: '验证数独失败' });
  }
});

// 获取游戏统计
router.get('/stats', async (req, res) => {
  try {
    const db = req.app.locals.db;
    
    const [stats] = await db.execute(`
      SELECT 
        COUNT(*) as total_games,
        COUNT(CASE WHEN completed = 1 THEN 1 END) as completed_games,
        AVG(CASE WHEN completed = 1 THEN score END) as avg_score,
        AVG(CASE WHEN completed = 1 THEN time_spent END) as avg_time,
        difficulty,
        COUNT(*) as games_by_difficulty
      FROM games 
      GROUP BY difficulty
    `);
    
    const [overallStats] = await db.execute(`
      SELECT 
        COUNT(*) as total_games,
        COUNT(CASE WHEN completed = 1 THEN 1 END) as completed_games,
        MAX(score) as best_score,
        MIN(CASE WHEN completed = 1 THEN time_spent END) as best_time
      FROM games
    `);
    
    res.json({
      success: true,
      data: {
        overall: overallStats[0],
        byDifficulty: stats
      }
    });
  } catch (error) {
    console.error('获取游戏统计失败:', error);
    res.status(500).json({ error: '获取游戏统计失败' });
  }
});

module.exports = router;